package service

import (
	"fabric-explorer/dao"
	"fabric-explorer/entity"
	"fabric-explorer/tools"
	"fmt"

	"github.com/hyperledger/fabric-sdk-go/pkg/fab"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
)

const (
	NODE_TYPE_PEER  string = "PEER"
	NODE_TYPE_ORDER string = "ORDERER"
	NODE_TYPE_CA    string = "CA"
)

//初始化节点数据
func InitNode() {
	nodeList := make([]entity.Node, 0)
	sdk := tools.SDKInit()
	defer sdk.Close()

	configBackend, err := sdk.Config()
	if err != nil {
		fmt.Printf("failed to get config backend, error: %s", err)
		return
	}

	endpointConfig, err := fab.ConfigFromBackend(configBackend)
	if err != nil {
		fmt.Printf("failed to get config backend, error: %s", err)
		return
	}
	networkPeers := endpointConfig.NetworkPeers()
	for _, np := range networkPeers {
		fmt.Printf("np.MSPID: %v\n", np.MSPID)
		fmt.Printf("np.URL: %v\n", np.URL)
		node := entity.Node{
			MSPID:    np.MSPID,
			Url:      np.URL,
			NodeType: NODE_TYPE_PEER,
		}
		nodeList = append(nodeList, node)
	}
	orderConfig := endpointConfig.OrderersConfig()
	for _, oc := range orderConfig {
		fmt.Printf("oc.URL: %v\n", oc.URL)
		node := entity.Node{
			MSPID:    "OrdererMSP",
			Url:      oc.URL,
			NodeType: NODE_TYPE_ORDER,
		}
		nodeList = append(nodeList, node)
	}
	//ca
	node := entity.Node{
		MSPID:    "Org1MSP",
		Url:      "ca_org1:17054",
		NodeType: NODE_TYPE_CA,
	}
	nodeList = append(nodeList, node)
	node = entity.Node{
		MSPID:    "Org2MSP",
		Url:      "ca_org2:27054",
		NodeType: NODE_TYPE_CA,
	}
	nodeList = append(nodeList, node)
	node = entity.Node{
		MSPID:    "Org3MSP",
		Url:      "ca_org3:37054",
		NodeType: NODE_TYPE_CA,
	}
	nodeList = append(nodeList, node)
	node = entity.Node{
		MSPID:    "OrdererMSP",
		Url:      "ca_orderer:9054",
		NodeType: NODE_TYPE_CA,
	}
	nodeList = append(nodeList, node)
	//去掉端口，设置name
	for i := 0; i < len(nodeList); i++ {
		node := &nodeList[i]
		node.Name = tools.GetNodeNameByUrl(node.Url)
	}
	//插入database
	for _, n := range nodeList {
		dao.InsertNode(n)
	}
}

//删除所有的Node数据
func DeleteAllNode() {
	dao.DeleteNode(bson.D{})
}

//获得所有的Node
func GetAllNode() []entity.Node {
	return dao.FindNodeList(bson.D{})
}

//获得所有的Node的数量
func GetNodeNum(selecter bson.D) int64 {
	return dao.GetNodeNum(selecter)
}

//查询page
func FindNodeListPage(selecter bson.D, options *options.FindOptions) []entity.Node {
	return dao.FindNodeListPage(selecter, options)
}
